package org.hawk.gwt.ppc.examples.generics;

import java.lang.reflect.ParameterizedType;
import java.util.AbstractList;

import org.hawk.gwt.ppc.reflect.lang.GWTClassType;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootPanel;
/**
 * Some examples for generic support are here. 
 * 
 * @author alex.bereznevatiy@gmail.com
 *
 * @param <T>
 */
public class Generics<T> extends AbstractList<String> implements EntryPoint {

	public void onModuleLoad() {
		final RootPanel rootPanel = RootPanel.get();
		
		ParameterizedType cls = (ParameterizedType) getClass().getGenericSuperclass();
		rootPanel.add(new HTML("Generic superclass type is: " + cls.toString().replace("<", "&lt;").replace(">", "&gt;")));
		
		// Notice that commented line below will not work 
		// because in GWT java.lang.Class is not a java.lang.reflect.Type
		// Class<?> parameter = (Class<?>) cls.getActualTypeArguments()[0];
		
		// This is recommended way of casting java.lang.reflect.Type to java.lang.Class
		GWTClassType<?> parameter = (GWTClassType<?>) cls.getActualTypeArguments()[0];
		rootPanel.add(new HTML("Generic superclass type parameter is: " + parameter.toString()));
		Class<?> parameterClass = parameter.toClass();
		rootPanel.add(new HTML("The same type as java.lang.Class: " + parameterClass.toString()));
	}

	public String get(int index) {
		if (index != 0) {
			throw new IndexOutOfBoundsException(String.valueOf(index));
		}
		return "Singleton";
	}

	@Override
	public int size() {
		return 1;
	}

}
